package counter.com.baomidou.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import counter.com.baomidou.entity.Log;
import counter.com.baomidou.entity.Serverinfo;
import counter.com.baomidou.entity.Targetinfo;
import counter.com.baomidou.entity.Trojan;
import counter.com.baomidou.service.ILogService;
import counter.com.baomidou.service.ITrojanService;
import counter.com.common.MyTool;
import counter.com.common.Result;
import counter.com.connproperty.Trojan.LogSimulateProperty;
import counter.com.connproperty.Trojan.logSearchProperty;
import counter.com.connproperty.targetinfo.TargetSearchProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-10-09
 */
@RestController
@RequestMapping("/log")
public class LogController {
    @Autowired
    ILogService logService;

    @Autowired
    ITrojanService trojanService;

    private static String[] descriptionPool = {"断开连接", "连接复位", "准备"};

    @PostMapping("/search")
    public Result search(@RequestBody logSearchProperty data) {
        LambdaQueryWrapper<Log> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(true, Log::getId);

        Page<Log> page = new Page<>(data.getPage(), data.getPagesize());
        IPage<Log> iPage = logService.page(page, wrapper);
        return Result.success(iPage);
    }


    @PostMapping("/simulate")
    public Result simulate(@RequestBody LogSimulateProperty data) {
        Integer trojanId = data.getTid();
        Trojan trojan = trojanService.getById(trojanId);
        if (trojan == null) {
            return Result.fail("未找到对应木马");
        }
        addSomeLogsAboutTrojan(trojan);
        return Result.success("成功添加");
    }

    private void addSomeLogsAboutTrojan(Trojan trojan) {
        int logNum = MyTool.getRandomInt(1, 4);
        for (int i = 0; i < logNum; i++) {
            Log log = new Log();
            log.setCreatedtime(LocalDateTime.now());
            log.setSrcip(trojan.getDstip());
            log.setSrcport(trojan.getDstport());
            log.setTargetname(trojan.getTargetname());
            log.setTargetusername(trojan.getDstusername());
            log.setOs(trojan.getOs());
            log.setDescription(generateRandomDescription());
            logService.save(log);
        }
    }

    private String generateRandomDescription() {
        return descriptionPool[MyTool.getRandomInt(0, descriptionPool.length)];
    }

}
